<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/22
 * Time: 11:44
 */
namespace app\admin\model;
use think\Db;

class DiGui{
    protected $dbname = 'column';
    protected $data = [];
    public function setDbName($name=null){
        if($name){
            $this->dbname = $name;
        }
        return $this;
    }
    public function getDbName(){
        return $this->dbname;
    }

    /**获取下级
     * @param int $pid
     * @param int $chengji
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getXiaJi($pid=0,$chengji=0,$mokuai_id=null){
        $data = Db::name(session('modular').'_'.$this->getDbName())
            ->where('pid',$pid);
        if($mokuai_id){
            $data = $data->where('mokuai_id',$mokuai_id);
        }
        $data = $data->where('delete_time',null)
            ->select();
        if(!$data){
            return [];
        }
        foreach ($data as $key=>$value){
            $data[$key]['xia'] = $this->getXiaJi($value['id'],$chengji+1);
            $data[$key]['cheng'] = $chengji;
        }
        return $data;
    }

    /**获取栏目
     * @param null $name
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function getColumn($name=null,$mokuai_id=null){
        $obj = new DiGui();
        if($name){
            $obj->setDbName($name);
        }else{
            $obj->setDbName('column');
        }
        return $obj->getXiaJi(0,0,$mokuai_id);
    }

    /**d递归获取数据
     * @param null $dbname
     * @param int $pid
     * @param int $cheng
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getData($dbname=null,$pid=0,$cheng=0){
        if($dbname){
            $this->setDbName($dbname);
        }
        $data = Db::name($this->dbname)->where('pid',$pid);
        if($this->dbname!==session('modular').'_roles'){
            $data = $data ->where('delete_time',null);
        }
        $data = $data->select();
        if(!$data){
            return false;
        }
        foreach ($data as $key=>$value){
            $value['cheng'] = $cheng;
            $this->data = array_merge($this->data,[$value]);
            $this->getData(null,$value['id'],$cheng+1);
        }
        return $this->data;
    }
}